#include "tcp_server.h"
#include <vector>
#include <functional>
#include <algorithm>
#include <thread>
#include <boost/bind.hpp>
#include "common/logger.h"


TcpServer::TcpServer(const std::string& port, const std::string addr)
	:io_server_(), 
	 acceptor_(io_server_), 
	 signal_set_(io_server_)
{
	//signal_set_.add(SIGINT);
	signal_set_.add(SIGTERM);
	signal_set_.async_wait(std::bind(&TcpServer::handlStop, this));

	tcp::resolver resolver(io_server_);
	tcp::resolver::query query(addr, port);
	tcp::endpoint endpoint = *resolver.resolve(query);
	acceptor_.open(endpoint.protocol());
	acceptor_.set_option(tcp::acceptor::reuse_address(true));
	acceptor_.bind(endpoint);
	acceptor_.listen();
}

void TcpServer::start(int thread_num)
{
	assert(thread_num >= 1);
	std::vector<std::thread*> threads;
	for (int i = 0; i < thread_num; ++i)
	{
		std::thread* worker = new std::thread(std::bind(&boost::asio::io_service::run, &io_server_));
		threads.push_back(worker);
	}
	startAccept();

	std::for_each(threads.begin(), threads.end(), std::mem_fun(&std::thread::join));
}

void TcpServer::startAccept()
{
	new_connection_.reset(new TcpConnection(io_server_));

	acceptor_.async_accept(new_connection_->socket(),
		std::bind(&TcpServer::onConnection, this, boost::asio::placeholders::error));
}

void TcpServer::onConnection(const boost::system::error_code& err)
{
	if (!err)
	{
		new_connection_->start();
	}
	else
	{
		LOG4CPLUS_ERROR(Log, "accept error: " << err.message());
	}

	startAccept();
}
